//
//  CallCenter.m
//  UtilsFundation
//
//  Created by zhou jianbang on 2019/4/24.
//

#import "CallCenter.h"
#import <CoreTelephony/CTCall.h>
#import <CoreTelephony/CTCallCenter.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

@interface CallCenter()

@property (nonatomic, strong) CTCallCenter *callCenter;
@property (nonatomic) BOOL callWasStarted;

@end

@implementation CallCenter

+(CallCenter *)shareManager
{
    static CallCenter * tool = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tool = [[CallCenter alloc] init];
        tool.callCenter = [[CTCallCenter alloc] init];
    });
    return tool;
}
-(void)startWatch;
{
    self.callWasStarted = NO;
    __weak __typeof__(self) weakSelf = self;
    [self.callCenter setCallEventHandler:^(CTCall *call) {
        
        if ([[call callState] isEqual:CTCallStateIncoming] ||
            [[call callState] isEqual:CTCallStateDialing]) {
            if (weakSelf.callWasStarted == NO) {
                weakSelf.callWasStarted = YES;
                if(weakSelf.callBack) weakSelf.callBack(@"connect");
            }
        } else if ([[call callState] isEqual:CTCallStateDisconnected]) {
            if (weakSelf.callWasStarted == YES)
            {
                weakSelf.callWasStarted = NO;
                if(weakSelf.callBack) weakSelf.callBack(@"disConnect");
            }
        }
    }];
}

+(void)startWatchCallBack:(CallBack)callBack
{
    CallCenter * callCenter = [CallCenter shareManager];
    callCenter.callBack = callBack;
    [callCenter startWatch];
}
@end
